package com.gzhryc.net_marketing.supplier.erp.services;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPICodeConstants;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.net_marketing.api.CloudGoodsAPIService;
import com.gzhryc.net_marketing.core.enums.EGoodsState;
import com.gzhryc.net_marketing.supplier.erp.dao.SupplierGoodsDao;
import com.gzhryc.net_marketing.supplier.erp.dao.db.SupplierGoods;
import com.gzhryc.net_marketing.supplier.erp.dao.enums.SupplierGoodsEnum;
import com.gzhryc.net_marketing.supplier.erp.services.dto.SupplierGoodsSearch;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SupplierGoodsService {

    static Logger log = Logger.getLogger(SupplierGoodsService.class);

    public static SupplierGoodsService self() {
        return MultiDBTools.getService(SupplierGoodsService.class, true);
    }

    public static SupplierGoodsService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, SupplierGoodsService.class, true);
    }

    SupplierGoodsDao dao;

    public SupplierGoodsService(String jdbcKey) {
        dao = new SupplierGoodsDao(jdbcKey);
    }

    public List<SupplierGoods> findJoinBySearch(SupplierGoodsSearch search, Integer pageNo, Integer pageLimit){
        Conditions condition = dao.buildConditions(search);
        condition.desc("createDate");
        try {
            return dao.findByCondition(condition,pageNo,pageLimit);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public Long countJoinBySearch(SupplierGoodsSearch search){
        Conditions condition = dao.buildConditions(search);
        try {
            return dao.countJoin(condition);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return 0L;
    }

    public SupplierGoods getById(Long id){
        if(id != null){
            try {
                return dao.getById(id);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public SupplierGoods getJoinById(Long id){
        if(id != null){
            try {
                return dao.getJoinById(id);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public SupplierGoods getByCode(String code){
        if(StringTools.isNotBlank(code)){
            Conditions condition = new Conditions(SupplierGoods.class);
            condition.and().is("code",code);
            try {
                return dao.get(condition);
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return null;
    }

    public boolean add(SupplierGoods goods) throws LogicException {
        if(goods.getPayMoney() == null){
            throw new LogicException("请设置零售价");
        }
        goods.setAuditState(SupplierGoodsEnum.AuditState.Wait.index());
        goods.setState(SupplierGoodsEnum.State.OffTheShelf.index());
        goods.setCreateDate(new Date());
        try {
            return dao.insert(goods) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }

    public boolean updateNotNull(SupplierGoods goods) throws LogicException {
        if(goods != null && goods.getId() != null) {
            SupplierGoods temp = this.getById(goods.getId());
            if(temp == null){
                throw new LogicException("未找到要修改的商品");
            }
            if(SupplierGoodsEnum.AuditState.Auditing.index().equals(temp.getAuditState())
                ||SupplierGoodsEnum.AuditState.Success.index().equals(temp.getAuditState())){
                throw new LogicException("商品正在发布中，不允许修改");
            }

            Conditions conditions = new Conditions(SupplierGoods.class);
            conditions.and().is("id",goods.getId());
            conditions.and().is("state",SupplierGoodsEnum.State.OffTheShelf.index());

            //修改的商品默认未审核
            goods.setAuditState(SupplierGoodsEnum.AuditState.Wait.index());
            goods.setAuditId(null);

            JdbcSession.begin();
            try {
                if(dao.updateNotNull(goods,conditions,"auditId") > 0){
                    if(SupplierGoodsEnum.AuditState.Success.index().equals(temp.getAuditState())) {
                        //修改云商品
                        DefaultAPIResponse apiResp = CloudGoodsAPIService.self().goodsUpdateState(temp.getCode(), EGoodsState.Delete.index());
                        if (apiResp != null && DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                            JdbcSession.commit();
                            return true;
                        }
                    }else{
                        JdbcSession.commit();
                        return true;
                    }
                }
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            } finally {
                JdbcSession.end();
            }
        }
        return false;
    }

    public boolean deleteById(Long id) throws LogicException{
        if(id != null){
            SupplierGoods goods = this.getById(id);
            if(goods == null){
                throw new LogicException("未找到商品信息");
            }
            JdbcSession.begin();
            try {
                if(dao.deleteById(id) > 0){
                    if(SupplierGoodsSpaceService.self().deleteByGoodsId(id)){
                        if(SupplierGoodsEnum.AuditState.Success.index().equals(goods.getAuditState())) {
                            //修改云商品
                            DefaultAPIResponse apiResp = CloudGoodsAPIService.self().goodsUpdateState(goods.getCode(), EGoodsState.Delete.index());
                            if (apiResp != null && DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                                JdbcSession.commit();
                                return true;
                            }
                        }else{
                            JdbcSession.commit();
                            return true;
                        }
                    }
                }
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }finally {
                JdbcSession.end();
            }
        }
        return false;
    }

    public boolean upGoods(Long id) throws LogicException{
        SupplierGoods goods = getById(id);
        if(goods == null){
            throw new LogicException("未找到商品信息");
        }

        if(!SupplierGoodsEnum.AuditState.Success.index().equals(goods.getAuditState())){
            throw new LogicException("商品未审核通过");
        }

        if(SupplierGoodsEnum.State.PutOnTheShelf.index().equals(goods.getState())){
            throw new LogicException("商品已上架");
        }

        SupplierGoods updateEntity = new SupplierGoods();
        updateEntity.setId(id);
        updateEntity.setState(SupplierGoodsEnum.State.PutOnTheShelf.index());

        JdbcSession.begin();
        try {
            if(dao.updateNotNull(updateEntity) > 0){
                //修改云商品
                DefaultAPIResponse apiResp = CloudGoodsAPIService.self().goodsUpdateState(goods.getCode(), EGoodsState.PutOnTheShelf.index());
                if (apiResp != null && DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                    goods.setState(updateEntity.getState());
                    JdbcSession.commit();
                    return true;
                }
            }
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }finally {
            JdbcSession.end();
        }
        return false;
    }

    public boolean downGoods(Long id) throws LogicException{
        SupplierGoods goods = getById(id);
        if(goods == null){
            throw new LogicException("未找到商品信息");
        }

        if(SupplierGoodsEnum.State.OffTheShelf.index().equals(goods.getState())){
            throw new LogicException("商品已下架");
        }

        SupplierGoods updateEntity = new SupplierGoods();
        updateEntity.setId(id);
        updateEntity.setState(SupplierGoodsEnum.State.OffTheShelf.index());

        JdbcSession.begin();
        try {
            if(dao.updateNotNull(updateEntity) > 0){
                //修改云商品
                DefaultAPIResponse apiResp = CloudGoodsAPIService.self().goodsUpdateState(goods.getCode(), EGoodsState.OffTheShelf.index());
                if (apiResp != null) {
                    if(DefaultAPICodeConstants.SUCCESS.equals(apiResp.getCode())) {
                        JdbcSession.commit();
                        return true;
                    }else if(DefaultAPICodeConstants.NULL_DATA.equals(apiResp.getCode())){
                        //删除商品发布
                        if (SupplierGoodsService.self().cancelAudit(goods.getId())){
                            JdbcSession.commit();
                            return true;
                        }
                    }else{
                        throw new LogicException(apiResp.getMsg());
                    }
                }
            }
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }finally {
            JdbcSession.end();
        }
        return false;
    }

    public boolean updateAuditResult(Long id,Long auditId,Integer auditState,String code,String auditNote) throws LogicException{
        if(id != null && auditState != null){
            Conditions condition = new Conditions(SupplierGoods.class);
            condition.and().is("id",id);

            Map<String,Object> data = new HashMap<>();
            data.put("auditId",auditId);
            data.put("auditState",auditState);
            data.put("code",code);
            data.put("auditNote",auditNote);

            try {
                return dao.update(data,condition) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }

    public boolean cancelAudit(Long id){
        if(id != null){
            Conditions condition = new Conditions(SupplierGoods.class);
            condition.and().is("id",id);

            Map<String,Object> data = new HashMap<>();
            data.put("auditId",null);
            data.put("auditState",SupplierGoodsEnum.AuditState.Cancel.index());
            data.put("code",null);
            data.put("auditNote",null);

            try {
                return dao.update(data,condition) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }
}
